package com.sjy.framework.codemultiplex;

import com.sjy.util.SpringUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.tools.*;
import java.io.File;
import java.net.*;
import java.util.*;


@Component
public class DynamicEngine  {
    private static MyClassLoader myClassLoader;

    public static Class<?> compile(String className, String javaCodes) {
        try {
            if(myClassLoader==null){

                URL[] urls = new URL[1];
                urls[0] = new File(System.getProperty("user.dir")).toURL();
                myClassLoader = new MyClassLoader(urls[0].getPath());
            }



        } catch (Exception e) {
            e.printStackTrace();
        }
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        StrSrcJavaObject srcObject = new StrSrcJavaObject(className, javaCodes);
        Iterable<? extends JavaFileObject> fileObjects = Collections.singletonList(srcObject);
        String flag = "-d";

        String outDir;
        File classPath;
        try {
            classPath = new File(Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).toURI());
            outDir = classPath.getAbsolutePath() + File.separator;
            Iterable<String> options = Arrays.asList(flag, outDir);
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, fileObjects);
            boolean result = task.call();
            if (result) {
                try {
                    return myClassLoader.loadClass(className);
                } catch (Exception e) {
                    System.out.println("加载失败!");
                    e.printStackTrace();
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        return null;
    }






}
